<template>
	<view>
		<view class="top">
		</view>
		<view class="address-container">
			<view class="address-list">
				<view v-for="(item, idx) in addressList" :key="item.id" class="address-item"
					@click="editAddress(item)">
					<view class="address-info">
						<text class="address-name">{{item.contacts}}</text>
						<text class="address-phone">{{item.phone}}</text>
						<text v-if="item.id == userInfo.defaultAddrId" class="default-tag">默认</text>
						<text v-else class="delete-tag" @click="delAddress(item)">删除</text>
					</view>
					<view class="address-detail">
						{{item.province}}{{item.city}}{{item.area}}{{item.detailsAddr}}
					</view>
				</view>
				<view v-if="!addressList" class="address-empty">暂无收货地址</view>
			</view>
			<view class="add-btn" @click="addAddress"
				style="z-index:10;position:relative;cursor:pointer; text-align: center;">
				+ 新增收货地址
			</view>
			<view v-if="showAddDialog" class="dialog-mask">
				<view class="dialog">
					<view class="dialog-title">{{info}}收货地址</view>
					<view class="dialog-body">
						<input v-model="addressForm.contacts" placeholder="收货人姓名" />
						<input v-model="addressForm.phone" placeholder="手机号" />
						<input v-model="addressForm.province" placeholder="省份" />
						<input v-model="addressForm.city" placeholder="城市" />
						<input v-model="addressForm.area" placeholder="地区" />
						<input v-model="addressForm.detailsAddr" placeholder="详细地址" />
						<view>
							<radio-group v-model="addressForm.isDefault">
								<label>
									<radio :value="1" @click="addressForm.isDefault=1" /> 默认
								</label>
								<label>
									<radio :value="0" @click="addressForm.isDefault=0"/> 非默认
								</label>
							</radio-group>
						</view>
					</view>
					<view class="dialog-footer">
						<button @click="submitAddress">提交</button>
						<button @click="showAddDialog = false">取消</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/uitls/request.js'

	export default {
		data() {
			return {
				userInfo:null,
				addressList: [],
				showAddDialog: false,
				info: '新增',
				addressForm: {
					id:0,
					province:'',
					city: '',
					area: '',
					detailsAddr: '',
					contacts: '',
					phone: '',
					isDefault: 0
				}
			}
		},
		onShow() {
			this.userInfo = uni.getStorageSync('userInfo')
			this.getUserAddress()
			// console.log(this.userInfo)
		},
		methods: {
			getUserAddress() {
				let userStr = this.userInfo
				if (!userStr) {
					console.log('未获取到本地用户信息')
					return
				}
				let user = typeof userStr === 'string' ? JSON.parse(userStr) : userStr
				let uid = user.id
				console.log('用户id:', uid)
				if (!uid) {
					console.log('用户id不存在')
					return
				}
				request({
					url: '/bigbase/address/getAddress/' + uid,
					method: 'GET',
					success: (res) => {
						// console.log('收货地址查询响应：', res.data)

						if (res.data.code == 200)
							this.addressList = res.data.rows
					}
				})
			},
			addAddress() {
				// alert('点击了新增收货地址按钮')
				this.info = '新增'
				this.addressForm = {
					id:0,
					province:'',
					city: '',
					area: '',
					detailsAddr: '',
					contacts: '',
					phone: '',
					isDefault: 0
				}
				this.showAddDialog = true
			},
			editAddress(address) {
				this.info = '修改'
				this.addressForm = address
				// console.log(this.addressForm)
				this.showAddDialog = true
			},
			delAddress(address){
				uni.showModal({
				    title: '提示',
				    content: '确定要删除这条数据吗？',
				    confirmText: '确认删除', // 自定义确认按钮文字
				    cancelText: '取消', // 自定义取消按钮文字
				    confirmColor: '#FF0000', // 确认按钮颜色
				    cancelColor: '#666666', // 取消按钮颜色
				    success: function (r) {
				        if (r.confirm) {
				            // 用户点击了确认按钮
				            // console.log('用户点击确认');
							request({
								url: '/bigbase/address/'+address.id,
								method: 'DELETE',
								success: (res) => {
									if(res.data.code==200){
										uni.showToast({
										  title: '删除成功', 
										  duration: 2000  ,// 设置一个较长的时间，避免自动消失
										  complete: () => { // Toast 显示完成后执行
											  this.getUserAddress()
											},
										})
									}
								}
							})
				            // 这里添加删除数据的逻辑
				        } else if (res.cancel) {
				            // 用户点击了取消按钮
				            console.log('用户点击取消');
				        }
				    },
				    fail: function (err) {
				        // 调用失败的回调函数
				        console.error('showModal 调用失败：', err);
				    }
				});
			},
			submitAddress() {
				let userStr = this.userInfo
				if (!userStr) {
					uni.showToast({
						title: '未获取到用户信息',
						icon: 'none'
					})
					return
				}
				let user = typeof userStr === 'string' ? JSON.parse(userStr) : userStr
				let uid = user.id
				if (!uid) {
					uni.showToast({
						title: '用户id不存在',
						icon: 'none'
					})
					return
				}
				// 简单校验
				const {
					province,
					city,
					area,
					detailsAddr,
					contacts,
					phone
				} = this.addressForm
				if (!province || !city || !area || !detailsAddr || !contacts || !phone) {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'none'
					})
					return
				}
				let address = {
					uid,
					...this.addressForm
				}
				console.log(address)
				const that = this
				let url = ''
				let method = 'POST'
				if(this.addressForm.id==0){
					url = '/add'					
				}else{
					method = 'PUT'
				}
				request({
					url:'/bigbase/address'+url,
					method: method,
					data: address,
					success: (res) => {
						if (res.data.code === 200) {
							uni.showToast({
								title: '操作成功',
								icon: 'success'
							})
							if(address.isDefault==1){
								// console.log(res.data)
								if(that.addressForm.id==0){
									that.userInfo.defaultAddrId = res.data.data
								}else{
									that.userInfo.defaultAddrId = address.id
								}
								
								uni.setStorageSync('userInfo',that.userInfo)
							}
							this.showAddDialog = false
							this.getUserAddress()
						} else {
							uni.showToast({
								title: res.data.msg || '添加失败',
								icon: 'none'
							})
						}
					}
				})
			}
		}
	}
</script>

<style>
	.top {
		width: 100%;
		height: 200px;
		background-color: #2979ff;
	}

	.address-list {
		margin-top: -185px;
	}

	.address-container {
		margin: 0 20px;
	}

	.address-item {
		background: #fff;
		border-radius: 10px;
		padding: 16px;
		margin-bottom: 14px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
		border: 2px solid transparent;
		position: relative;
	}

	.address-default {
		border: 2px solid #2979ff;
	}

	.address-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 6px;
	}

	.address-name {
		font-size: 16px;
		color: #333;
		font-weight: bold;
	}

	.address-phone {
		font-size: 15px;
		color: #888;
	}

	.address-detail {
		font-size: 14px;
		color: #666;
	}

	.address-empty {
		background-color: #fff;
		text-align: center;
		color: #bbb;
		width: 100%;
		height: 400rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 20px;
	}

	.add-btn {
		width: 100%;
		margin-top: 30px;
		background: #2979ff;
		color: #fff;
		border-radius: 24px;
		font-size: 16px;
		height: 44px;
		line-height: 44px;
		border: none;
	}

	.default-tag {
		background: #2979ff;
		color: #fff;
		font-size: 12px;
		border-radius: 8px;
		padding: 2px 8px;
		margin-left: 10px;
		vertical-align: middle;
	}
	.delete-tag {
		background: #e46962;
		color: #fff;
		font-size: 12px;
		border-radius: 8px;
		padding: 2px 8px;
		margin-left: 10px;
		vertical-align: middle;
	}

	.dialog-mask {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.dialog {
		background: #fff;
		border-radius: 10px;
		padding: 20px;
		width: 80vw;
	}

	.dialog-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.dialog-body input,
	.dialog-body view {
		margin-bottom: 10px;
		width: 100%;
	}

	.dialog-footer {
		display: flex;
		justify-content: space-between;
	}
</style>